package com.rain.shoppingscienceproj.ui.activity.login;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rain.shoppingscienceproj.R;
import com.rain.shoppingscienceproj.http.BaseSubscriber;
import com.rain.shoppingscienceproj.http.ExceptionHandle;
import com.rain.shoppingscienceproj.http.RetrofitClient;
import com.rain.shoppingscienceproj.module.UserInfo;
import com.rain.shoppingscienceproj.ui.activity.BaseActivity;
import com.rain.shoppingscienceproj.ui.activity.MainActivity;
import com.rain.shoppingscienceproj.ui.activity.register.RegisterActivity;
import com.rain.shoppingscienceproj.ui.base.GlobalData;
import com.rain.shoppingscienceproj.ui.utile.DeviceUtils;
import com.rain.shoppingscienceproj.ui.utile.PowerUtils;
import com.rain.shoppingscienceproj.utils.AppManager;
import com.rain.shoppingscienceproj.utils.LoadingDialog;
import com.rain.shoppingscienceproj.utils.SharedPreferencesUtil;
import com.rain.shoppingscienceproj.utils.ToolPhone;
import com.rain.shoppingscienceproj.utils.toast.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import okhttp3.ResponseBody;

public class LoginActivity extends BaseActivity {


    @BindView(R.id.et_mobile)
    EditText et_mobile;
    @BindView(R.id.et_password)
    EditText et_password;
    @BindView(R.id.btn_login)
    Button btn_login;
    @BindView(R.id.tv_main)
    TextView tv_main;

    private int flag = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        AppManager.getAppManager().addActivity(this);
        ButterKnife.bind(this);
//        PowerUtils.getIMEI(this);
        flag = getIntent().getIntExtra("type", 0);
        loadingDialog = new LoadingDialog(this, "正在加载...");
        initData();
        if (flag == 0) {
            tv_main.setVisibility(View.VISIBLE);
        } else {
            tv_main.setVisibility(View.GONE);
        }
        initListener();
    }

    private void initData() {
        final String userData = SharedPreferencesUtil.getString(LoginActivity.this, "AppShopping", "AppShopping", "");
        if (userData != null && !userData.equals("")) {
            Gson gson = new Gson();
            UserInfo userInfo = gson.fromJson(userData, UserInfo.class);
            GlobalData.setUserInfo(userInfo);
            startActivitys(MainActivity.class);
            finish();
        }
    }

    private void initListener() {

    }


    @OnClick(R.id.btn_login)
    void login() {
        String deviceId = DeviceUtils.getUniqueId(this);
        String mobile = et_mobile.getText().toString().trim();
        if (mobile.isEmpty()) {
            ToastUtils.showLongToast("请输入手机号码");
            return;
        }
        boolean isPhone = ToolPhone.isMobileNO(mobile);
        if (!isPhone) {
            ToastUtils.showShortToast("手机号码格式错误");
            return;
        }
        String password = et_password.getText().toString().trim();
        if (password.isEmpty()) {
            ToastUtils.showLongToast("请输入密码");
            return;
        }
        loadingDialog.show();
        RetrofitClient.getInstance(this)
                .createBaseApi()
                .login(mobile, password, deviceId, new BaseSubscriber<ResponseBody>(this) {
                    @Override
                    public void onError(ExceptionHandle.ResponeThrowable e) {
                        ToastUtils.showLongToast("网络错误");
                        loadingDialog.dismiss();
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        super.onNext(responseBody);
                        loadingDialog.dismiss();
                        try {
                            String request = responseBody.string();
                            JSONObject json = new JSONObject(request);
                            int code = json.getInt("code");
                            if (code == 0) {
                                JSONObject jsonData = json.getJSONObject("data");
                                String jsonString = jsonData.getString("user");
                                String tokens = jsonData.getString("token");
                                TypeToken<UserInfo> token = new TypeToken<UserInfo>() {
                                };
                                UserInfo userInfo = new Gson().fromJson(jsonString, token.getType());
                                JPushInterface.setAlias(LoginActivity.this, 1, userInfo.getDeviceid());
                                userInfo.setToken(tokens);
                                userInfo.setUserId(userInfo.getId());
                                GlobalData.setUserInfo(userInfo);
                                SharedPreferencesUtil.putString(LoginActivity.this, "AppShopping", "AppShopping", new Gson().toJson(userInfo));
                                if (flag == 0) {
                                    startActivitys(MainActivity.class);
                                }
                                finish();
                            } else {
                                ToastUtils.showShortToast(json.getString("message"));
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    @OnClick(R.id.tv_forget_password)
    void forget() {
        startActivitys(RegisterActivity.class, 2);
    }

    @OnClick(R.id.tv_register)
    void register() {
        startActivitys(RegisterActivity.class, 1);
    }

    @OnClick(R.id.tv_main)
    void main() {
        startActivitys(MainActivity.class);
        finish();
    }
}
